package mvc.struts.form;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class StrutsXml {

	public StrutsXml()
	{
		
	}
	
	/**
	 * 
	 * @param xmlPath
	 * @return
	 * @throws Exception
	 */
	public static Map<String, XmlBean>	Struts_Xml(String xmlPath) throws Exception
	{
		SAXBuilder	builder = new SAXBuilder();
		
		Document	document = builder.build(new File(xmlPath));
		
		Element		root = document.getRootElement();
		
		Map<String, XmlBean>	bean_map = new HashMap<String, XmlBean>();
		
		Element		actionRoot = root.getChild("action-mapping");
		
		List<Element>	action = actionRoot.getChildren();
		
		for	(Element e : action)
		{
			XmlBean	actionBean = new XmlBean();
			
			String	name = e.getAttributeValue("name");
			actionBean.setBeanName(name);
			
			Element	actionform = root.getChild("formbeans");
			List<Element>	form = actionform.getChildren();
			
			for	(Element el : form)
			{
				if	(name.equals(el.getAttributeValue("name")))
				{
					String	formclass = el.getAttributeValue("class");
					actionBean.setFormClass(formclass);
					break;
				}
			}
			
			String	path = e.getAttributeValue("path");
			actionBean.setPath(path);
			
			String	type = e.getAttributeValue("type");
			actionBean.setActionType(type);
			
			List<Element>	forward = e.getChildren();
			Map<String, String>	forward_map = new HashMap<String, String>();
			
			for	(Element x : forward)
			{
				String	fname  = x.getAttributeValue("name");
				String	fvalue = x.getAttributeValue("value");
				
				forward_map.put(fname,  fvalue);
			}
			
			actionBean.setActionForward(forward_map);	
			bean_map.put(path, actionBean);
		}
		
		return	bean_map;
	}
	
	/**
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		

		//Map<String, XmlBean> m = new StrutsXml.Struts_Xml("/WEB-INF/struts_xml.xml");
	}

}
